package com.qfjy.project.meeting;

import com.qfjy.common.util.result.ResultCode;
import com.qfjy.common.util.result.ResultJson;
import com.qfjy.entity.po.User;
import com.qfjy.project.threadPools.MessageThread;
import com.qfjy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    private MessageThread messageThread = new MessageThread();

    @Resource
    private UserService userService;

    @GetMapping("/login")
    @ResponseBody
    public Object login(@RequestParam("email") final String email,
                        @RequestParam("wid") final String wid,
                        @RequestParam("openid")String openid){


        User user = userService.getUserByEmail(email);
        if (user==null){
            return new ResultJson<>("邮箱不存在", ResultCode.NOT_DATA);
        }else {
            if (user.getWid()!=null){
                return new ResultJson<>("该邮箱已被其他用户绑定,请联系管理员",ResultCode.SUCCESS_IS_HAVE);
            }else {
                int num = userService.updateUserWidByEmail(wid, email);
                log.info("用户绑定成功{}--{}",wid,email);

                String content = "恭喜" + user.getName() + "绑定成功";

                // 发送邮件
                messageThread.sendEmail(user.getEmail(),"恭喜用户" + user.getName() + "绑定成功");

                // 发送短信
                messageThread.sendSMS(user.getTelephone());

                // 发送微信消息
                messageThread.sendWeChatMessage(openid, content);

                // 关闭线程池
                messageThread.shutdown();
                return new ResultJson<>(num,ResultCode.SUCCESS);
            }
        }
    }

    /**
     * todo 个人中心 更新(更改个人信息)
     */
    @PostMapping("/updateUser")
    @ResponseBody
    public ResultJson updateUser(User user) {
        int num = 0;
        try {
            num = userService.updateByPrimaryKeySelective(user);
        } catch (Exception e) {
            log.error("用户的传参导致数据库的异常:{}--->{}", user.toString(), e.getMessage());
            return new ResultJson(num, ResultCode.EXCEPTION);
        }
        log.info("个人中心-用户信息修改成功{}", user);

        return new ResultJson(num, ResultCode.SUCCESS);
    }

}
